<template>
  <div>
    <el-tree ref="roleTree" node-key="id" show-checkbox check-strictly :data="permissionList" default-expand-all :props="{ label: 'name'}" />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
import { getRoleId, assignPerm } from '@/api/setting'

export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [] // 权限列表
    }
  },
  created() {
    // console.log(this.roleId)
    // 调用获取权限列表的方法
    this.getPermissionList()
    // 调用api回显 用户权限
    this.getRoleId()
  },
  methods: {
    // 获取员工权限
    async getRoleId() {
      const res = await getRoleId(this.roleId)
      // 获取树形组件将获取的平面权限数据转化为树形且通过node-key="id" 绑定复选框 渲染
      this.$refs.roleTree.setCheckedKeys(res.data.permIds)
    },
    // 获取权限列表
    async getPermissionList() {
      // 调用api 获取权限列表
      const res = await getPermissionList()
      if (!res.success) return this.$message.error(res.message)
      // 将获取的数据转化为树形数据
      this.permissionList = transListToTree(res.data, '0')
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      // 获取权限id
      const permIds = this.$refs.roleTree.getCheckedKeys()
      // 为员工分配权限
      const res = await assignPerm({ id: this.roleId, permIds })
      // 提示消息
      this.$message.success(res.message)
      // 关闭弹框 (通信)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
